#include <vector>
#include <iostream>
#include <string>
#include <cassert>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "Task.hpp"
using namespace std;
const int num = 5;
static int number = 1;
class channel
{
public:
    channel(int fd, int id)
        : ctrlfd(fd), workerid(id)
    {
        name = "channel-" + to_string(number++);
    }

public:
    int ctrlfd;
    pid_t workerid;
    string name;
};

// 传参约定
// 1.输入参数 const &
// 2.输出参数 *
// 3.输入输出参数 &

void work()
{
    while (true)
    {
        int code = 0;
        ssize_t n = read(0, &code, sizeof(code));
        if (n == sizeof(code))
        {
            if (!init.CheckSafe(code))
                continue;
            init.Runtask(code); // 执行任务
        }
        else if (n == 0) // 当写端关闭了，读端一直读取，会读取到文件结尾，也就是0
        {
            break;
        }
        else
        {
        }
    }
    cout << "child quit..." << endl;
}

void PrintFd(const vector<int> &fds)
{
    cout << getpid() << " close fds: ";
    for (auto fd : fds)
    {
        cout << fd << " ";
    }
    cout << endl;
}

void CreateChannels(vector<channel> *c)
{
    vector<int> old;
    for (int i = 0; i < num; i++)
    {
        // 1.创建管道
        int pipefd[2];
        int n = pipe(pipefd);
        assert(n == 0);
        (void)n;

        // 2.创建子进程
        pid_t id = fork();
        assert(id != -1);
        if (id == 0)
        {
            if (!old.empty())
            {
                for (auto e : old)
                {
                    close(e);
                }
                PrintFd(old);
            }
            // 子进程
            close(pipefd[1]); // 子进程关闭写端
            dup2(pipefd[0], 0);
            work();
            exit(0);
        }
        close(pipefd[0]);
        c->push_back(channel(pipefd[1], id)); // 插入父的文件描述符，子的pid
        old.push_back(pipefd[1]);
    }
}

void PrintDebug(const vector<channel> &c)
{
    for (const auto &channel : c)
    {
        cout << channel.ctrlfd << ", " << channel.workerid << ", " << channel.name << endl;
    }
}

void SendCommand(const vector<channel> &c, bool flag, int num = -1)
{
    int pos = 0;
    while (true)
    {
        // 1. 选择任务
        int command = init.SelectTask();

        // 2. 选择信道(进程)
        const auto &channel = c[pos++];
        pos %= c.size();

        // debug
        std::cout << "send command " << init.ToDesc(command) << "[" << command << "]"
                  << " in "
                  << channel.name << " worker is : " << channel.workerid << std::endl;

        // 3. 发送任务
        write(channel.ctrlfd, &command, sizeof(command));

        // 4. 判断是否要退出
        if (!flag)
        {
            num--;
            if (num <= 0)
                break;
        }
        sleep(1);
    }

    std::cout << "SendCommand done..." << std::endl;
}

void ReleaseChannels(const vector<channel> &c)
{
    for (const auto &e : c)
    {
        close(e.ctrlfd); // 将写端的所有文件描述符关掉
        waitpid(e.ctrlfd, nullptr, 0);
    }
}
int main()
{
    vector<channel> channels;
    // 1.创建管道，创建进程
    CreateChannels(&channels);

    // 2.开始发送任务
    const bool g_always_loop = true;
    SendCommand(channels, !g_always_loop, 10);

    // 3.回收资源，想让子进程退出，并释放管道，只要关闭写端
    ReleaseChannels(channels);

    return 0;
}